package com.cman777.springc.common.helper;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author chenzhicong
 * @time 2020/1/21 15:02
 * @description
 */
public class StringTemplateUtil {
    private static Pattern templatePattern = Pattern.compile("\\$\\{(\\w+)\\}");

    /**
     * 模板替换，变量形式为${xxx}形式。
     */
    public static String templateEngine(String template, Map<String, ?> params) {
        StringBuffer sb = new StringBuffer();
        Matcher matcher = templatePattern.matcher(template);
        while (matcher.find()) {
            String key = matcher.group(1);
            Object value = params.get(key);
            matcher.appendReplacement(sb, value != null ?
                    Matcher.quoteReplacement(value.toString()) : "");
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}
